package session;

import game.Game;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

import shared.io.startup.PlayerStartup;

public class Session extends Thread {

   private Socket serverSocket;
   private ObjectInputStream in;
   private ObjectOutputStream out;
   private Object inObject;
   private ObjectManager objectManager;
   private Game game;
   private boolean alive;
   
   public Session(Game game) {
      this.game = game;
   }
   
   /**
    * Start up the session. Connect to the server.
    */
   public void init(String ip, int port, String name) {
      try {
         if (alive) {
            close();
         }
         objectManager = new ObjectManager(game);
         serverSocket = new Socket(ip, port);
         out = new ObjectOutputStream(serverSocket.getOutputStream());
         in = new ObjectInputStream(serverSocket.getInputStream());
         writeObject(new PlayerStartup(name));
      } catch (UnknownHostException e) {
         close();
      } catch (IOException e) {
         close();
      }
      
   }

   @Override
   public void run() {
      try {
         while(alive && (inObject = in.readObject()) != null) {
            objectManager.manageObject(inObject);
         }
      } catch (IOException e) {
         close();
      } catch (ClassNotFoundException e) {
         close();
      } finally {
         close();
      }
   }
   
   /**
    * Sends an object to the server.
    */
   public void writeObject(Object object) {
      try {
         out.writeObject(object);
      } catch (IOException e) { }
   }
   
   /**
    * Closes the clientSession
    */
   public void close() {
      try {
         Date date = new Date();
         System.out.println(date.getTime());
         System.out.println("CLOSING");
         alive = false;
         in.close();
         out.close();
         serverSocket = null;
         objectManager = null;
      } catch (IOException e) {}

   }
   
   @Override
   public void start() {
      if (!alive) super.start();
      alive = true;
   }
   
}
